package com.cyzy.controller;

import com.cyzy.entity.RequestDTO;
import com.cyzy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器 - 处理Token刷新等认证相关功能
 */
@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "*")
public class AuthController {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 刷新Token
     * 在Token即将过期前调用此接口获取新Token
     */
    @PostMapping("/refresh-token")
    public RequestDTO refreshToken(@RequestHeader("Authorization") String authHeader) {
        try {
            String oldToken = authHeader.substring(7); // 移除 "Bearer " 前缀
            
            // 验证旧Token（即使过期也允许在短时间内刷新）
            if (jwtUtil.validateToken(oldToken)) {
                // 获取用户ID
                Integer userId = jwtUtil.getUserIdFromToken(oldToken);
                
                // 生成新Token
                String newToken = jwtUtil.generateToken(String.valueOf(userId));
                
                Map<String, Object> result = new HashMap<>();
                result.put("token", newToken);
                result.put("userId", userId);
                result.put("message", "Token刷新成功");
                
                return new RequestDTO(200, "Token刷新成功", result);
            } else {
                return new RequestDTO(401, "Token已过期，请重新登录", null);
            }
        } catch (Exception e) {
            return new RequestDTO(500, "Token刷新失败: " + e.getMessage(), null);
        }
    }
    
    /**
     * 检查Token状态
     */
    @GetMapping("/check-token")
    public RequestDTO checkToken(@RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7);
            
            if (jwtUtil.validateToken(token)) {
                Integer userId = jwtUtil.getUserIdFromToken(token);
                
                Map<String, Object> result = new HashMap<>();
                result.put("valid", true);
                result.put("userId", userId);
                result.put("message", "Token有效");
                
                return new RequestDTO(200, "Token有效", result);
            } else {
                return new RequestDTO(401, "Token无效或已过期", null);
            }
        } catch (Exception e) {
            return new RequestDTO(500, "Token检查失败", null);
        }
    }
}

